<template>
  <div class="main commodity-tag-list">
    <div v-if="rightsButtons['add']" class="tool-bar">
      <el-button type="success" icon="el-icon-plus" class="fr" @click="showAdd(1)">新建一级分类</el-button>
    </div>
    <tree-table v-loading="listLoading" :data="list" :columns="columns" :eval-args="args" :expand-all="true" border>
      <el-table-column align="center" label="是否可用" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.status == 1 ? '可用' : '不可用' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="排序" width="80" prop="sort"></el-table-column>
      <el-table-column v-if="rightsButtons['addSub'] || rightsButtons['edit'] || rightsButtons['delete']" align="left" label="操作" width="260">
        <template slot-scope="scope">
          <el-button v-if="rightsButtons['addSub']&&scope.row._level!==3" type="success" size="mini" @click="showAdd(scope.row)">新建子类</el-button>
          <el-button v-if="rightsButtons['edit']" type="primary" size="mini" @click="showEdit(scope.row)">编辑</el-button>
          <el-button v-if="rightsButtons['delete']" type="danger" size="mini" @click="del(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </tree-table>
    <el-dialog :title="editItem.id ? '编辑分类' : '新建分类'" :visible.sync="showEditPop">
      <el-form ref="editItem" :model="editItem" size="medium" label-width="120px">
        <!-- 一级显示 -->
        <el-form-item v-if="categoryLevel === 1" label="模板类型:" prop="templateType" :rules="commonRules.notNullRule">
          <el-select v-model="editItem.templateType" :disabled="editItem.id ? true : false">
            <el-option label="素材模板" :value="1"></el-option>
            <el-option label="产品模板" :value="2"></el-option>
            <el-option label="文章模板" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <!-- 二级显示 -->
        <el-form-item v-if="categoryLevel === 2" label="模板属性:" prop="templateProperties" :rules="commonRules.notNullRule">
          <el-select v-if="editItem.templateType!=2" v-model="editItem.templateProperties" :disabled="editItem.id ? true : false">
            <el-option label="全版(官方)" :value="1"></el-option>
            <el-option v-if="editItem.templateType!=3" label="简版(个人)" :value="2"></el-option>
          </el-select>
          <el-select v-if="editItem.templateType===2" v-model="editItem.templateProperties" :disabled="editItem.id ? true : false">
            <el-option label="全版(商品)" :value="1"></el-option>
            <el-option v-if="editItem.templateType!=3" label="简版(产品)" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类标题:" prop="title" :rules="commonRules.notNullRule">
          <el-input v-model="editItem.title" maxlength="8" placeholder="输入不超过8个字"></el-input>
        </el-form-item>
        <el-form-item label="分类副标:" prop="subTitle">
          <el-input v-model="editItem.subTitle" maxlength="8" placeholder="输入不超过8个字"></el-input>
        </el-form-item>
        <el-form-item label="icon图标:" prop="icon">
          <el-upload
            class="avatar-uploader"
            accept="image/jpg,image/jpeg,image/png,image/gif"
            :action="upladUrl"
            name="file"
            :show-file-list="false"
            :on-success="uploadIconSuccess"
            :before-upload="beforeUpload">
            <img v-if="editItem.icon" :src="editItem.icon" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="banner图片:" prop="banner">
          <el-upload
            class="avatar-uploader"
            accept="image/jpg,image/jpeg,image/png,image/gif"
            :action="upladUrl"
            name="file"
            :show-file-list="false"
            :on-success="uploadSuccess"
            :before-upload="beforeUpload">
            <img v-if="editItem.banner" :src="editItem.banner" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="排序:" prop="sort" :rules="commonRules.fakerNumRule">
          <el-input v-model="editItem.sort" placeholder="输入纯数字值越大越前面"></el-input>
        </el-form-item>
        <!-- 文章模板----有“跳转类型” -->
        <el-form-item v-if="editItem.templateType===3" label="跳转类型:" prop="haveUrl" :rules="commonRules.notNullRule">
          <el-radio-group v-model="editItem.haveUrl">
            <el-radio :label="false">无</el-radio>
            <el-radio :label="true">URL</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="editItem.templateType===3&&editItem.haveUrl" prop="directUrl" :rules="commonRules.urlRule">
          <el-input v-model="editItem.directUrl" placeholder="输入URL仅支持内置H5链接"></el-input>
        </el-form-item>
        <el-form-item label="是否可用:" prop="status">
          <el-switch
            v-model="editItem.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="btnDisabled" @click="save">确认添加</el-button>
        <el-button @click="showEditPop = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import treeTable from '@/components/TreeTable'

export default {
  name: 'biQuanCategory',
  components: {
    treeTable
  },
  data() {
    return {
      list: [],
      columns: [
        {
          text: '分类名称',
          value: 'title'
        }
      ],
      args: [null, null, 'title'],
      params: {
        name: ''
      },
      editItem: {},
      editName: '',
      categoryLevel: 0,
      showEditPop: false,
      listLoading: false,
      btnDisabled: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取列表
    getList() {
      this.listLoading = true
      this.request({
        url: '/zhongcao-web-manage/social-material-category/list',
        method: 'get'
      }).then(({ data }) => {
        this.list = data || []
        this.listLoading = false
      }).catch(err => {
        this.list = []
        this.listLoading = false
      })
    },
    beforeUpload(file) {
      const testmsg = /^image\/(jpg|jpeg|png|gif)$/.test(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!testmsg) {
        this.$message.error('上传图片格式不对!')
        return
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!')
      }
      return testmsg && isLt5M
    },
    // 删除
    // 当分类已被帖子关联，不允许删除----“该分类已被引用，不可删除”---确认
    del(item) {
      this.$alert('请谨慎考虑，删除后不可见', '确认删除该分类', {
        confirmButtonText: '确认删除',
        center: true
      }).then(() => {
        this.request({
          url: '/zhongcao-web-manage/social-material-category/delete',
          method: 'post',
          data: {
            id: item.id,
            level: item._level
          }
        }).then((res) => {
          if (res.data === false) {
            this.$alert('', '该分类已被引用，不可删除', {
              confirmButtonText: '确认',
              center: true
            })
          } else {
            this.$message.success('删除成功')
          }
          this.getList()
        }).catch(err => {
          console.log(err)
        })
      })
    },
    // 显示新建
    showAdd(item) {
      this.editItem = {
        banner: '',
        directUrl: '',
        icon: '',
        id: 0,
        parentId: 0,
        sort: '', // 排序
        status: 0, // 0-未启用，1-已启动
        subTitle: '',
        templateProperties: 1, //	模板属性：1-全版(官方)1, 2-简版(个人)
        templateType: 1, // 模板类型：1-素材模板, 2-产品模板, 3-文章模板
        title: '',
        haveUrl:false
      }
      if (item && item.id) {
        this.editItem.parentId = item.id
        this.categoryLevel = item._level + 1
        this.editItem.templateProperties = item.templateProperties
        this.editItem.templateType = item.templateType
      } else {
        this.categoryLevel = item
      }
      this.showEditPop = true
      this.btnDisabled = false
    },
    // 显示编辑
    showEdit(item) {
      item.haveUrl = item.directUrl != ''
      this.editItem = { ...item }
      this.editItem.id = item.id
      this.editItem.parentId = item.parentId
      this.categoryLevel = item._level
      this.showEditPop = true
      this.btnDisabled = false
    },
    uploadIconSuccess(res, file) {
      this.$set(this.editItem, 'icon', this.replaceImgUrl(res.filePath))
    },
    uploadSuccess(res, file) {
      this.$set(this.editItem, 'banner', this.replaceImgUrl(res.filePath))
    },
    // 保存
    save() {
      this.$refs.editItem.validate(valid => {
        if (!valid) {
          return false
        }
        if (this.editItem.haveUrl === false) {
          this.editItem.directUrl = ''
        }
        const { banner, directUrl, icon, id, parentId, sort, status, subTitle, templateProperties, templateType, title } = this.editItem
        const data = {}
        this.btnDisabled = true
        this.request({
          url: '/zhongcao-web-manage/social-material-category/save',
          method: 'post',
          data: {
            banner,
            directUrl,
            icon,
            id,
            parentId,
            sort,
            status,
            subTitle,
            templateProperties,
            templateType,
            title
          }
        }).then((res) => {
          this.btnDisabled = false
          this.editItem = {}
          this.$nextTick(()=>{
            this.$refs.editItem.clearValidate()
          });
          this.showEditPop = false
          this.$message.success('保存成功')
          this.getList()
        }).catch(err => {
          console.log(err)
          this.btnDisabled = false
        })
      })
    }
  }

}
</script>
